package com.minggo.charmword.logic;

import java.util.Map;

import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

import com.google.gson.Gson;
import com.minggo.charmword.cache.CacheUtils;
import com.minggo.charmword.model.Result;
import com.minggo.charmword.model.User;
import com.minggo.charmword.net.ApiUrl;
import com.minggo.charmword.net.ApiUtil;
import com.minggo.charmword.util.UserUtil;

/**
 * 用户注册
 * 
 * @author minggo
 * @time 2014-9-21 S下午9:26:17
 */
public class UserRegisterUtil extends AsyncTask<Void, Void, User> {

	private Handler handler;
	private String email;
	private String password;
	public static final int USER_REGISTER = 10002;
	public static final int USER_REGISTER_FAILED = 10003;
	private Gson gson = new Gson();
	private String phone;
	private double latitude;
	private double longitude;
	private String address;
	private Result result;

	public UserRegisterUtil(Handler handler, String email, String password, String phone,double latitude,double longitude,String address) {
		this.handler = handler;
		this.email = email;
		this.password = password;
		this.phone = phone;
		this.latitude = latitude;
		this.longitude = longitude;
		this.address = address;
	}

	@Override
	protected User doInBackground(Void... param) {

		String key = "user_info";
		Map<String, Object> params = ApiUtil.addRequiredParam();
		params.put("password", password);
		params.put("email", email);
		params.put("phone", phone);
		params.put("sex", "male");
		params.put("sex", "male");
		params.put("latitude", latitude);
		params.put("longitude", longitude);
		params.put("address", address);
		result = ApiUtil.getResultByPost(ApiUrl.USER_REGISTER, params, null, false, "");
		if (null == result) {
			return null;
		}
		
		try {
			User user = new Gson().fromJson(result.content, User.class);
			
			if (user != null) {
				Log.i("regist", "username--->" + user.username);
				CacheUtils.getInstance().setDiskCache(key, gson.toJson(user));
				return user;
			}
		} catch (Exception e) {
			e.printStackTrace();
			// Log.e(PARSE_JSON, "获取用户信息 -->"+e.toString());
		}
		return null;

	}

	@Override
	protected void onPostExecute(User user) {
		super.onPostExecute(user);
		if (result!=null&&!result.success) {
			handler.obtainMessage(USER_REGISTER_FAILED, result).sendToTarget();
		}else{
			handler.obtainMessage(USER_REGISTER, user).sendToTarget();
		}
	}
}
